﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Globalization;

namespace PMC
{
    public class Updater : Interfaces.IUpdatable
    {
        public Version CurrentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
        public Version OnlineVersion
        { get; set; }

        /// <summary>
        /// Checks the RSS-feed for a newer version
        /// </summary>
        /// <returns></returns>
        public Uri PerformUpdate()
        {
            if (!Global.CheckInternetConnection())
                throw new ConnectionException();
            try
            {
                var xml = new XmlDocument();
                xml.Load(Properties.Settings.Default.UpdateUri);

                var items = xml.GetElementsByTagName("item");
                var item = items[0];
                var date = DateTime.Parse(item["pubDate"].InnerText, CultureInfo.InvariantCulture);

                var link = item["link"].InnerText;
                return Assembly.GetExecutingAssembly().ExtractDateTime() < date ? new Uri(link) : null;
            }
            catch (Exception e)
            {
                Log.Instance.AddMessage(e);
                throw;
            }
        }
    }
}
